﻿// Write a program that deletes from given text file all odd lines. 
// The result should be in the same file.

using System;
using System.IO;

class DeleteOddLinesFromFile
{
    static void Main()
    {
        string path = @"..\..\";

        string inputFileName = "file.txt";
        string inputFile = Path.Combine(path, inputFileName);

        try
        {
            DeleteOddLinesInFile(inputFile);
            Console.WriteLine("All odd lines from file {0} are deleted.", inputFile);
        }
        catch (Exception exc)
        {
            Console.WriteLine(exc.Message);
        }
    }

    static void DeleteOddLinesInFile(string inputFile)
    {
        string outputFileName = "temp.txt";
        string path = Path.GetDirectoryName(inputFile);
        string outputFile = Path.Combine(path, outputFileName);

        using (FileStream fileStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        using (BufferedStream bufferedStream = new BufferedStream(fileStream))
        using (StreamReader reader = new StreamReader(bufferedStream))
        using (StreamWriter writer = new StreamWriter(outputFile))
        {
            int lineNumber = 1;
            while (!reader.EndOfStream)
            {
                string currentLine = reader.ReadLine();
                if (lineNumber % 2 == 0)
                {
                    writer.WriteLine(currentLine);
                }

                lineNumber++;
            }
        }

        File.Replace(outputFile, inputFile, Path.ChangeExtension(inputFile, ".bak"));
    }
}